# -*- coding: utf-8 -*-
from __future__ import print_function
import sys
import tempfile
import os
import json
import maya.cmds as cmds
import pymel.core as pm
import maya.utils as utils
import errno
import uuid

web_meassage = {"sendclient":"maya",'to':'blender',"data":{}}

### file -import -type "FBX"  -ignoreVersion -ra true -mergeNamespacesOnClash false -namespace "Cube" -options "fbx"  -pr  -importTimeRange "combine" "C:/Users/linchun/AppData/Local/Temp/Cube.fbx";
def export_selected_meshes_separately():
    # Maya 中需要额外导入 cmds 模块
    
    selected_objects = cmds.ls(selection=True)
    mesh_objects = []
    for obj in selected_objects:
        shapes = cmds.listRelatives(obj, shapes=True, type='mesh')
        if shapes:
            mesh_objects.append(obj)
    
    if not mesh_objects:
        print(u"没有选择MESH类型的对象")
        return []
    
    temp_dir = tempfile.gettempdir()
    print(temp_dir)
    results = []
    
    try:
        for obj in mesh_objects:
            cmds.select(clear=True)
            cmds.select(obj)
            
            export_path = os.path.join(temp_dir, "{0}.fbx".format(obj))  # 修改为兼容Python 2.7的字符串格式化
            
            try:
                cmds.file(export_path, force=True, options="v=0;", type="FBX export", preserveReferences=True, exportSelected=True)
                results.append((obj, export_path))
            except Exception as e:
                print(u"导出 {0} 失败: {1}".format(obj, str(e)))  # 添加unicode前缀解决乱码
    finally:
        cmds.select(selected_objects)
    
    return results

def send_to_blender():
    export_results = export_selected_meshes_separately()
        
    if not export_results:
        print({'WARNING'}, "No mesh objects selected")
        return {'CANCELLED'}
    else:
        web_meassage['data'] = export_results
        print(web_meassage)
        send_to_file(web_meassage)
    for model_name, export_path in export_results:
        print("Exported: {0} -> {1}".format(model_name, export_path))  # 修改为兼容Python 2.7的字符串格式化
    
    print("{0}".format({'INFO'}), "Exported {0} objects".format(len(export_results)))  # 修改为兼容Python 2.7的字符串格式化
    return {'FINISHED'}


def on_message(message):
    u"""
    处理接收到的 WebSocket 消息
    :param message: 接收到的消息字符串
    """
    try:
        try:
            data = json.loads(message)
            if data.get('to') == 'maya':
                for model_info in data.get('data', []):
                    if len(model_info) >= 2:
                        fbx_path = model_info[1].replace('\\\\\\\\','\\')
                        print(fbx_path)
                        # mel_cmd = f'file -import -type "FBX"  -ignoreVersion -ra true  -options "fbx"  -namespace "link_mod" -importTimeRange "override" "{fbx_path}";'
                        # print(mel_cmd)
                        try:
                            # 先删除同名模型
                            model_name = os.path.basename(fbx_path).split('.')[0]
                            if cmds.objExists(model_name):
                                cmds.delete(model_name)
                                print("已删除旧模型: {0}".format(model_name))
                            
                            # 导入新模型
                            pm.importFile(fbx_path, type="FBX")
                            print("成功导入 {0}".format(fbx_path))  # 修改为兼容Python 2.7的字符串格式化
                        except Exception as import_e:
                            print("导入 {0} 失败: {1}".format(fbx_path, str(import_e)))  # 修改为兼容Python 2.7的字符串格式化
        except json.JSONDecodeError:
            print(u"消息不是有效的 JSON 格式")
    except Exception as e:
        print(u"处理消息时出错: {0}".format(str(e)))


def send_to_file(message):

    # 确保交换目录存在
    exchange_dir = os.path.join(tempfile.gettempdir(), "MayaToBlender")
    try:
        os.makedirs(exchange_dir)
    except OSError:
        if not os.path.isdir(exchange_dir):
            raise
    
    # 创建唯一的文件名
    filename = "maya_message_{0}.json".format(uuid.uuid4())
    file_path = os.path.join(exchange_dir, filename)
    
    # 写入消息数据
    with open(file_path, 'w') as f:
        json.dump(message, f)
    
    print(u"消息已写入文件: {0}".format(file_path))


def start_file_listener():

    
    exchange_dir = os.path.join(tempfile.gettempdir(), "BlenderToMaya")
    try:
        os.makedirs(exchange_dir)
    except OSError as e:
        if e.errno != errno.EEXIST:
            raise
    
    def check_for_messages():
        # 检查目录中的所有文件
        try:
            for filename in os.listdir(exchange_dir):
                if filename.endswith('.json'):
                    file_path = os.path.join(exchange_dir, filename)
                    try:
                        # Python 3兼容性处理
                        with open(file_path, 'r', encoding='utf-8') as f:
                            message = json.load(f)
                        # 处理消息
                        on_message(json.dumps(message))
                        # 删除已处理的文件
                        os.remove(file_path)
                    except Exception as e:
                        print(u"处理文件 {0} 时出错: {1}".format(filename, str(e)))
        except Exception as e:
            print(u"检查消息目录时出错: {0}".format(str(e)))
        return True  # 保持定时器运行
    
    def run_file_listener():
         try:
            check_for_messages()
            utils.executeDeferred(run_file_listener)
         except Exception as e:
             print(u"文件监听出错: {0}".format(str(e)))
     
    utils.executeDeferred(run_file_listener)
    print(u"文件监听已启动")